<?php

namespace app\api\controller;

use addons\epay\library\Service;
use app\common\controller\Api;
use app\common\model\Addclock;
use app\common\model\Amount;
use app\common\model\Area;
use app\common\model\CommentZan;
use app\common\model\Config;
use app\common\model\Coupon;
use app\common\model\InformLog;
use app\common\model\InviteLog;
use app\common\model\MoneyLog;
use app\common\model\OrderComment;
use app\common\model\OrderServe;
use app\common\model\ParentMoneyLog;
use app\common\model\PlatForm;
use app\common\model\Recharge;
use app\common\model\Serve;
use app\common\model\StoreMoneyLog;
use app\common\model\Technician;
use app\common\model\TechnicianServe;
use app\common\model\Urge;
use app\common\model\UseCoupon;
use app\common\model\User;
use app\common\service\Pay;
use Exception;
use PDOException;
use think\Db;
use think\Loader;


class Order extends Api
{
    protected $noNeedLogin = ['time_technicianlist','gnotifyx','notifyx','returnx','test'];
    protected $noNeedRight = ['*'];


    /**
     * 服务评论列表
     * type 0 全部 1 好评 2 中评 3 差评 4 有图
     */
    public function servecommentlist(){
        $type=$this->request->request('type');
        $uid=$this->auth->id;
        $serve_id=$this->request->request('serve_id');
        if(!$serve_id){
          $this->error('参数不能为空');
        }
        if($type){
          $where['type']=$type;
        }
        $where['serve_id']=$serve_id;
        $comment=OrderComment::where($where)->field('id,star,createtime,content,image,uid,technician_id,serve_id,type,address')->select();
      $haoping=OrderComment::where(['star'=>5,'serve_id'=>$serve_id])->count();
      $zhongping=OrderComment::where(['star'=>['in',[2,3,4]],'serve_id'=>$serve_id])->count();
      $chaping=OrderComment::where(['star'=>1,'serve_id'=>$serve_id])->count();
      $quanbu=OrderComment::where(['serve_id'=>$serve_id])->count();
      $youtu=OrderComment::where(['store_id'=>$serve_id,'type'=>4])->count();
        $serve=\app\common\model\Serve::where('id','=',$serve_id)->field('id,serve_name')->find();
        foreach ($comment as $k=>$v){
          $technician=Technician::where(['technician_id'=>$v['technician_id']])->field('technician_id,technician_avatar,technician_name')->find();
          $user=\app\common\model\User::where(['id'=>$v['uid'],'postion'=>1])->field('id,avatar,nickname')->find();
            //点赞状态
          $v['zan_status']=Db::name('comment_zan')->where(['comment_id'=>$v['id'],'uid'=>$uid])->value('zan')??2;//1已点赞 2取消点赞
           //点赞数量
            $v['zan_count']=Db::name('comment_zan')->where(['comment_id'=>$v['id'],'zan'=>1])->count();
            $comment_count=[];
         $technician['serve']=$serve;
         $v['technician']=$technician;
         $v['user']=$user;
            $comment_count['haoping']=$haoping;
            $comment_count['zhongping']=$zhongping;
            $comment_count['chaping']=$chaping;
            $comment_count['quanbu']=$quanbu;
            $comment_count['youtu']=$youtu;
          $v['image']=explode(',',$v['image']);
         $v['createtime']=date('Y-m-d H:i',$v['createtime']);
        }
        $this->success('查询成功',['comment'=>$comment,'comment_count'=>$comment_count??[]]);
    }

    /**
     * 评论点赞
     */

    public function commentZan(){
        $uid        = $this->auth->id;
        $comment_id= $this->request->request('comment_id');//评论ID
      $postion=$this->request->request('postion');//1 用户 2 技师
      if(!$comment_id){
        $this->error('参数不能为空');
      }
      $comment=OrderComment::where(['id'=>$comment_id])->find();
      if(!$comment){
        $this->error('评论不存在');
      }
        $type       = $this->request->request('type');//1 点赞  2取消点赞
        if($type==1){
$oldzan=CommentZan::where(['uid'=>$uid,'comment_id'=>$comment_id])->find();
            if($oldzan['zan'] == 1){
                $this->error('您已经点过赞');
            }
            if($oldzan['zan'] == 2){
                $data = [
                    'uid'        => $uid,
                    'comment_id' => $comment_id,
                    'zan'        => 1,
                    'createtime' => time(),
                    'postion'=>$postion
                ];
    $res= CommentZan::where('comment_id',$comment_id)->update($data);
            }else{
                $data = [
                    'uid'        => $uid,
                    'comment_id' => $comment_id,
                    'zan'        => 1,
                    'createtime' => time(),
                     'postion'=>$postion
                    ];
              $res=CommentZan::create($data);
            }
            if($res){
                $this->success('点赞成功');
            }else{
                $this->error('点赞失败');
            }
        }else if($type == 2){
$oldzan=CommentZan::where(['uid' => $uid, 'comment_id' => $comment_id, 'zan' => 1])->find();
  if($oldzan){
   $res=CommentZan::where('comment_id', $comment_id)->update(['zan' => 2]);
    if($res){
        $this->success('取消点赞成功');
    }else{
        $this->error('取消点赞失败');
    }
}
        }
    }


    /**
     * 举报投诉
     * order_id 订单id
     * inform_id 举报原因
     * name 投诉人姓名
     * technician_nickname 投诉技师昵称
     * phone 投诉人电话
     * content 内容
     * images 证据图片
     */

    public function OrderInform(){
        $uid=$this->auth->id;
        $order_id=$this->request->request('order_id');
        $inform_id=$this->request->request('inform_id');
        $name=$this->request->request('name');
        $technician_nickname=$this->request->request('technician_nickname');
        $content=$this->request->request('content');
        $images=$this->request->request('images');
        $phone=$this->request->request('phone');
        if(!$inform_id ||!$order_id){
            $this->error('参数不能为空');
        }
        $order=\app\common\model\Order::get($order_id);
        if(!$order){
            $this->error('当前订单不存在');
        }
        $technician_id=$order['technician_id'];
        $store_id=$order['store_id'];

        $data=[
            'uid'=>$uid,
            'order_id'=>$order_id,
            'inform_title'=>$inform_id,
            'name'=>$name,
            'content'=>$content,
            'phone'=>$phone,
            'images'=>$images,
            'technician_nickname'=>$technician_nickname,
            'is_sendto'=>1,
            'inform_time'=>time(),
             'store_id'=>$store_id,
             'technician_id'=>$technician_id
        ];
        $res=InformLog::create($data);
    if($res){
        $this->success('举报成功');
    }else{
        $this->error('举报失败');
    }
    }

    /**
     * 订单列表
     * type 1 待付款 2 待服务 3 待评价
     */

    public function OrderList(){

      $uid=$this->auth->id;
      $type     = $this->request->request('type');
      $is_store=$this->request->request('is_store');
      $page     = $this->request->request('page')?:1;
//      if (!in_array($type,[1,2,3])) {
//        $this->error("请求类型错误");
//      }
      $where = [];

      if($is_store==1){
      $where['is_store_order']=1;
      }else if($is_store===0||$is_store==='0'){
        $where['is_store_order']=0;
      }
      if($type==1){
        $where['order_status']=['in',[0]];
      }else if($type==2){
        $where['order_status']=['in',[2,3,4]];
      }else if($type==3){
        $where['order_status']=['in',[6]];
      }else{
        $where=[];
      }
      $where['uid'] =$uid;
      $time=config('site.countdown');
      $orderlist    = \app\common\model\Order::where($where)->field('id,uid,store_id,serve_id,order_status,appointment_time,is_store_order,order_amount,order_time,mileagefee')->order('createtime','desc')->page($page,10)->select();
      foreach ($orderlist as $key=>$value){
        $value['store']=\app\common\model\Store::where('store_id',$value['store_id'])->field('store_id,name,phone')->find();
        $value['serve_info']=\app\common\model\Serve::where('id',$value['serve_id'])->field('id,serve_name,serve_image,serve_price')->find();
        $value['await_time']=$time*60- (time() - $value['order_time']);
      }
      $this->success('', $orderlist);
    }

//返回退款金额


    public function  refundprice(){
      $uid=$this->auth->id;
      $type=$this->request->request('type');//1 已付款待接单申请退款 2 已付款已接单
      $order_id=$this->request->request('order_id');
      if($type==1){
          $order=\app\common\model\Order::where(['id'=>$order_id,'uid'=>$uid,'order_status'=>1])->find();
          if($order){
              $serve=\app\common\model\Serve::where(['id'=>$order->serve_id])->field('serve_price')->find();
              $refund_price=$serve->serve_price;
          }
      }else if(in_array($type,[2,3,4])){
          $order=\app\common\model\Order::where(['id'=>$order_id,'order_status'=>['in',[2,3,4]]])->find();
          if($order){
              $serve=\app\common\model\Serve::where(['id'=>$order->serve_id])->field('serve_price')->find();
              $round_fare=$order->mileagefee;
              $refund_price=bcsub($serve->serve_price,$round_fare,2);
          }
      }
      $this->success('',['refund_price'=>$refund_price??[]]);
    }


    /**
     * 申请退款
     * 技师接单前申请退款(全退)
     * 技师接完单申请退款
     */


    public function applyRefund(){
      $uid=$this->auth->id;
      $postion=$this->auth->postion;
      if($postion!=1){
        $this->error('当前身份不是用户');
      }

      $money=$this->request->request('money');
      $order_id=$this->request->request('order_id');//申请退款的订单

      $order=\app\common\model\Order::where(['id'=>$order_id,'uid'=>$uid])->find();
      if(!$order){
        $this->error('订单不存在');
      }
      if($order->payment_type== 3){
        \app\common\model\User::money($money, $uid, '技师已接单用户申请退款(扣车费)', 1,$postion,1);
      }else{
        if($order->pay_time!=0){
          $result=Pay::refund($order,'技师已接单用户申请退款(扣车费)', $money);
          if(!$result){
            $this->error('付款原路退回出错');
          }
        }
      }
        $order['refund_status']=1;
        $order['order_status']=9;
        $order['refund_money']=$money;
        $order->save();
      $this->success('操作成功');
    }



    /**
     * 删除订单
     */

    public function del_order(){

      $uid=$this->auth->id;
      $order_id=$this->request->request('order_id');
      $order=\app\common\model\Order::where(['uid'=>$uid,'id'=>$order_id])->find();
      if(!$order){
        $this->error('订单不存在');
      }
      $res=$order->delete();
      if($res){
        $this->success('删除成功');
      }else{
        $this->error('删除失败');
      }

    }

    /**
     * 取消订单
     * $type 1 未支付取消订单 2 待接单取消订单
     */

    public function cancelOrder(){
      $uid=$this->auth->id;
      $order_id=$this->request->request('order_id');
      $order=\app\common\model\Order::where(['id'=>$order_id,'uid'=>$uid])->find();
      if(!$order){
        $this->error('订单不存在');
      }
          if($order->order_status!=0){
              $this->error('订单状态异常');
          }
          $res=\app\common\model\Order::where(['id'=>$order_id,'uid'=>$uid])->update(['order_status'=>7,'cancel_time'=>time()]);
//      }else if($type==2) {
//          if ($order->order_status != 1) {
//              $this->error('订单状态异常');
//          }
//          if ($order->payment_type == 3) {
//              \app\common\model\User::money($order->order_amount, $uid, '技师待接单用户取消订单', 1,1,1);
//          } else {
//              $result = Pay::refund($order, '技师待接单用户取消订单', $order->order_amount);
//              if (!$result) {
//                  $this->error('付款原路退回出错');
//              }
//          }
//          $res=\app\common\model\Order::where(['id'=>$order_id,'uid'=>$uid])->update(['order_status'=>13,'cancel_time'=>time(),'refund_status'=>1,'refund_money'=>$order->order_amount]);
//      }
   if($res){
     $this->success('取消成功');
   }else{
     $this->error('取消失败');
   }
    }

    /**
     * 订单详情
     */
    public function OrderDetail(){
      $uid                    = $this->auth->id;
      $postion=$this->auth->postion;
     $where=[];
      $order_id               = $this->request->request('order_id');
      if(!$order_id){
          $this->error('参数不能为空');
      }
      $where['id']=$order_id;
      $store=\app\admin\model\Store::where(['uid'=>$uid])->find();
      if($store){
          $store_id=$store['store_id'];
          $where['store_id']=$store_id;
      }
      $technician=Technician::where(['uid'=>$uid])->find();
      if($technician){
          $where['technician_id']=$technician['technician_id'];
      }
      $order=\app\common\model\Order::where($where)->field('id,technician_id,store_id,address_id,order_time,pay_time,order_status,order_note,appointment_time,serve_id,u_address,order_amount,order_amounts,mileagefee,coupon_money,distance,quantity,createtime,order_sn,serve_id,detail,uname,phone,u_address')->find();
    if($order){
      $order['technician_info'] = Technician::where('technician_id', $order->technician_id)->field('technician_id,technician_avatar,technician_name,technician_phone,technician_fraction')->find();
      $order['technician_info']['technician_fraction']=$order['technician_info']['technician_fraction']??5;
        $weekarray=array("日","一","二","三","四","五","六"); //先定义一个数组
        $week=$weekarray[date("w",strtotime( $order['appointment_time']))];
        $order['week']='周'.$week;

      $address_info= \app\common\model\Address::where('id', $order->address_id)->field('username,id,mobile,detail,address')->find();
      if(!$address_info){
        $address_info['username']=$order['uname'];
        $address_info['mobile']=$order['phone'];
        $address_info['address']=$order['detail'];
          $address_info['detail']=$order['u_address'];
      }
      $order['store_info']=\app\common\model\Store::where(['store_id'=>$order->store_id])->field('store_id,name,phone')->find();
      $order['serve_info']=Serve::where(['id'=>$order['serve_id']])->field('serve_name,serve_image,serve_duration,serve_price')->find();
      $order['address_info']=$address_info;

      $time=config('site.countdown');
     if($postion==1){
         $order['await_time']=$time*60- (time() - $order->createtime);
         $order['await_money']=$order->order_amount;
     }
      $order['order_time']=date('Y-m-d H:i', $order->order_time);
     if($order['pay_time']){
         $order['order_time']=date('Y-m-d H:i', $order->pay_time);
     }else{
         $order['pay_time']=0;
     }
    }
      $this->success('',  $order??[]);
    }



    /**
     * 订单追踪
     */

    public function ordertrack(){
      $uid=$this->auth->id;
      $order_id=$this->request->request('order_id');
      $order=\app\common\model\Order::where(['id'=>$order_id,'uid'=>$uid])->field('order_time,pay_time,departure_time,beginserve_time,endserve_time,receiving_time,arrive_time,add_bell_time,comment_time')->find();
      if($order){
        if($order['pay_time']){
          $order['pay_time'] = date('Y-m-d H:i:s', $order['pay_time']);
        }else{
          $order['pay_time']=0;
        }
        if($order['order_time']){
          $order['order_time'] = date('Y-m-d H:i:s', $order['order_time']);
        }else{
          $order['order_time']=0;
        }
        if($order['departure_time']){
          $order['departure_time'] = date('Y-m-d H:i:s', $order['departure_time']);
        }else{
          $order['departure_time']=0;
        }
        if($order['beginserve_time']){
          $order['beginserve_time'] = date('Y-m-d H:i:s', $order['beginserve_time']);
        }else{
          $order['beginserve_time']=0;
        }
        if($order['endserve_time']){
          $order['endserve_time'] = date('Y-m-d H:i:s', $order['endserve_time']);
        }else{
          $order['endserve_time']=0;
        }
        if($order['receiving_time']){
          $order['receiving_time'] = date('Y-m-d H:i:s', $order['receiving_time']);
        }else{
          $order['receiving_time']=0;
        }
        if($order['arrive_time']){
          $order['arrive_time'] = date('Y-m-d H:i:s', $order['arrive_time']);
        }else{
          $order['arrive_time']=0;
        }
        if($order['add_bell_time']){
          $order['add_bell_time'] = date('Y-m-d H:i:s', $order['add_bell_time']);
        }else{
          $order['add_bell_time']=0;
        }
        if($order['comment_time']){
          $order['comment_time'] = date('Y-m-d H:i:s', $order['comment_time']);
        }else{
          $order['comment_time']=0;
        }
      }
      $this->success('查询成功',$order);
    }


  /**
   * 技师订单追踪,当前技师订单
   */

  public function technician_track(){
    $uid=$this->auth->id;
    $postion=$this->auth->postion;
    $order_id=$this->request->request('order_id');
    if(!$order_id){
      $this->error('参数不能为空');
    }
    $technician=Technician::where(['uid'=>$uid])->find();
    $order=\app\common\model\Order::where(['id'=>$order_id])->field('order_time,pay_time,departure_time,beginserve_time,endserve_time,receiving_time,arrive_time,add_bell_time,comment_time,order_status')->find();
    if($postion==2){
      $order=\app\common\model\Order::where(['id'=>$order_id,'technician_id'=>$technician->technician_id])->field('order_time,pay_time,departure_time,beginserve_time,endserve_time,receiving_time,arrive_time,add_bell_time,comment_time,order_status')->find();
    }else if($postion==3){
      $store=\app\admin\model\Store::where(['uid'=>$uid])->find();
      $order=\app\common\model\Order::where(['id'=>$order_id,'store_id'=>$store->store_id])->field('order_time,pay_time,departure_time,beginserve_time,endserve_time,receiving_time,arrive_time,add_bell_time,comment_time,order_status')->find();
    }
    if($order){
      if($order['pay_time']){
        $order['pay_time'] = date('Y-m-d H:i:s', $order['pay_time']);
      }else{
        $order['pay_time']=0;
      }
      if($order['order_time']){
        $order['order_time'] = date('Y-m-d H:i:s', $order['order_time']);
      }else{
        $order['order_time']=0;
      }
      if($order['departure_time']){
        $order['departure_time'] = date('Y-m-d H:i:s', $order['departure_time']);
      }else{
        $order['departure_time']=0;
      }
      if($order['beginserve_time']){
        $order['beginserve_time'] = date('Y-m-d H:i:s', $order['beginserve_time']);
      }else{
        $order['beginserve_time']=0;
      }
      if($order['endserve_time']){
        $order['endserve_time'] = date('Y-m-d H:i:s', $order['endserve_time']);
      }else{
        $order['endserve_time']=0;
      }
      if($order['receiving_time']){
        $order['receiving_time'] = date('Y-m-d H:i:s', $order['receiving_time']);
      }else{
        $order['receiving_time']=0;
      }
      if($order['arrive_time']){
        $order['arrive_time'] = date('Y-m-d H:i:s', $order['arrive_time']);
      }else{
        $order['arrive_time']=0;
      }
      if($order['add_bell_time']){
        $order['add_bell_time'] = date('Y-m-d H:i:s', $order['add_bell_time']);
      }else{
        $order['add_bell_time']=0;
      }
      if($order['comment_time']){
        $order['comment_time'] = date('Y-m-d H:i:s', $order['comment_time']);
      }else{
        $order['comment_time']=0;
      }
      $this->success('查询成功',$order??[]);
    }

  }

    /**
     * 订单详情修改地址
     */

    public function updAddress(){
        $uid=$this->auth->id;
        $order_id=$this->request->request('order_id');
        $name=$this->request->request('name');
        $gender=$this->request->request('gender');
        $phone=$this->request->request('phone');
        $uaddress=$this->request->request('uaddress');
        if(!$order_id){
           $this->error('参数错误');
        }
        $order=\app\common\model\Order::where(['uid'=>$uid,'id'=>$order_id])->find();
        if($order['change_address']==2){
            $this->error('您已修改过一次地址,不能再次修改');
        }
        $order_data = [
            'phone' => $phone,
           'uname'=>$name,
            'gender'=>$gender,
            'u_address'=>$uaddress,
            'change_address'=>2
        ];
        $res        = \app\common\model\Order::where('id', $order_id)->update($order_data);
        if($res){
            $this->success('修改成功');
        }else{
            $this->error('修改失败');
        }
    }


    /**
     * 订单地址查询
     */

    public function OrderAddress(){
        $uid=$this->auth->id;
        $order_id=$this->request->request('order_id');

        $order=\app\common\model\Order::where(['id'=>$order_id,'uid'=>$uid])->find();
        if($order){
            $address=\app\common\model\Address::where(['uid'=>$uid,'id'=>$order['address_id']])->field('id,address')->find();
        }
        $this->success('',$address);
    }


    /**
     * 订单服务查询,
     * 可加服务查询
     */

    public function OrderServe(){
        $uid=$this->auth->id;
        $order_id=$this->request->request('order_id');
        if(!$order_id){
          $this->error('参数不能为空');
        }
        $order=\app\common\model\Order::where(['id'=>$order_id,'uid'=>$uid])->find();
        if($order){
            $serve_ids=TechnicianServe::where('technician_id','in',$order->technician_id)->group('serve_id')->column('serve_id');
            $serve=\app\common\model\Serve::where(['serve_status'=>1,'id'=>['in',$serve_ids]])->field('id,serve_name,serve_duration,serve_price')->select();
          $this->success('',$serve);
        }
        $this->success('查询成功',[]);

    }


  /**
   * 订单交通费
   */

  public function mileagefee($lon,$lat,$technician_id ,$appointment_time){
    $technician=Technician::where(['technician_id'=>$technician_id])->find();
//    $address=\app\common\model\Address::where(['id'=>$address_id])->find();
    $distance         = distance($lon,$lat,$technician->lon, $technician->lat);
    $appointment_time = date('H', strtotime($appointment_time));//获取是白天还是晚上
    $day_times        = config('site.day');   //白天
    $night_times      = config('site.night'); //晚上
    $mileage_cost     = 0;
    if($appointment_time >= $day_times && $appointment_time <= $night_times){
      if($distance > config('site.free_mileage')){
        $mileage_exceeded = $distance - config('site.free_mileage');//总里程-免费里程
        $mileage_cost     = bcmul($mileage_exceeded, config('site.kilometer_cost'), 2) * 2;//超出里程*里程单价  超出里程费用
      }else{
        $distance ;
      }
    }else{
      if($distance > config('site.free')){
        $mileage_exceeded = $distance - config('free');//总里程-免费里程
        $mileage_cost     = bcmul($mileage_exceeded, config('site.kilometer_nightcost'), 2) * 2;//超出里程*里程单价  超出里程费用
      }else{
        $distance;
      }
    }

    return ['mileage_cost' =>  $mileage_cost, 'distance' => $distance];
  }


    /**
     * 创建订单
     */

    public function createOrder()
    {

      $uid = $this->auth->id;
      $technician_id = $this->request->request('technician_id');//技师id
      $address_id = $this->request->request('address_id',0);//地址id
      $serve_id = $this->request->request('serve_id');//服务id
      $order_note = $this->request->request('order_note', '');//订单备注
      $uname = $this->request->request('uname');//客户名
      $uaddress = $this->request->request('uaddress');//门牌号
        $udetail=$this->request->request('udetail');//服务地址
      $gender = $this->request->request('gender');//下单人姓名 0 女 1 男
      $phone = $this->request->request('phone');//下单人手机号
      $appointment_time = $this->request->request('appointment_time');//预约时间
      $coupon_id = $this->request->request('coupon_id',0);//优惠券id
      $quantity = $this->request->request('quantity');//服务数量
      $address = \app\common\model\Address::where(['id' =>$address_id])->find();
      if(!$address){
          $lon=$this->request->request('lon');
          $lat=$this->request->request('lat');
      }else{
          $lon=$address['lon'];
          $lat=$address['lat'];
          $udetail=$address['detail'];
          $uaddress=$address['address'];
          $phone =$address['mobile'];
          $uname =$address['username'];
      }
      $technician = Technician::get($technician_id);
      $serve = \app\common\model\Serve::where(['id' => $serve_id])->find();
      $store = \app\common\model\Store::where(['store_id' => $technician['store_id']])->find();
      $serve_price = $serve->serve_price;
      $serve_time = $serve->serve_duration * $quantity;
      $order_amount = bcmul($serve_price, $quantity, 2);//订单原价
      if (!$technician) {
        $this->error('该技师不存在');
      }
      if($serve->serve_status!=1){
          $this->error('该服务还未审核通过');
      }
//      if(!$technician['serve_time']&&$technician['serve_time_end']){
//        $this->error('该技师暂未上传工作时间');
//      }
      $day=datetime($appointment_time,'w');

      $technicians=Technician::where(['work_day'=>['like',"%$day%"]])->find();
      if(!$technicians){
        $this->error('当前不在技师工作日内');
      }
      if ($technician['store_id'] == 0) {
        $this->error('该技师还未加入店铺');
      }
     $tserve=TechnicianServe::where(['technician_id'=>$technician_id,'serve_id'=>$serve_id])->find();
      if(!$tserve){
        $this->error('该技师没有该服务');
      }
      $order=\app\admin\model\Order::where(['uid' => $uid, 'order_status' => 0])->find();
      if($order){
          $this->error('你有一笔待支付的订单',['order_id'=>$order['id']],1);
      }
      $book_start_time=strtotime($appointment_time);
      $book_end_time=$book_start_time+$serve_time*60;
      $order = \app\common\model\Order::where(['uid' => $uid])->select();
      if (!$order) {
        $first_discount = Config('site.first_discount');
        $order_amount = bcsub($serve_price, $first_discount, 2);
      }
      if ($coupon_id) {
        $coupon_info = UseCoupon::where(['coupon_id' => $coupon_id])->find();
        $coupon_money = Coupon::where(['id' => $coupon_info['coupon_id']])->value('term');
        if ($order_amount >= $coupon_money) {
          $coupon_price = Coupon::where(['id' => $coupon_info['coupon_id']])->value('money');
        } else {
          $coupon_price = 0;
        }
      } else {
        $coupon_price = 0;
      }
      if(!$address){
          $roundinfo = $this->mileagefee($lon,$lat,$technician_id, $appointment_time);//路程信息
      }else{
          $roundinfo = $this->mileagefee($lon,$lat,$technician_id, $appointment_time);//路程信息
      }
      $round_mileage = $roundinfo['distance']; //里程
      $round_fare = $roundinfo['mileage_cost'];//里程价格

      if ($round_mileage['distance'] > 50) {
        $this->error('距离过远,请联系平台客服');
      }
        $inviteinfo             = \app\admin\model\User::where('id',$uid)->find();
      $first_level_commission = 0;
      $sub_commission = 0;
      if($inviteinfo&&$inviteinfo['inviter_id']){
          $last_userinfo = \app\common\model\User::get($inviteinfo['inviter_id']);//上级用户信息
          if ($last_userinfo) {
              $sub_commission = bcmul($order_amount, config('site.sub_commission') / 100, 2);//上级分佣
              $twoinfo = \app\admin\model\User::where('id', $last_userinfo['inviter_id'])->find(); //根据上级ID查询上上级ID
              if ($twoinfo) {
                  $twolast_info = \app\common\model\User::get($twoinfo['id']);//上上级用户信息
                  if ($twolast_info) {
                      $first_level_commission = bcmul($order_amount, config('site.first_level_commission') / 100, 2);//上上级分佣
                  } else {
                      $first_level_commission = 0;
                  }
              }
          } else {
              $sub_commission = 0;
          }
      }
      //平台抽成
      $platform_commission = bcmul($order_amount, config('site.platform_commission') / 100, 2);

      //店铺分佣
      if ($technician['store_id'] != 0 && $technician['is_join_store'] == 1) {
        $store_money = bcmul($order_amount, config('site.store_commission') / 100, 2);
      } else {
        $store_money = 0;
      }
      //技师分佣
      $technician_commission = bcsub($order_amount, $platform_commission, 2);//技师分佣
      $technician_commission = $store_money ?bcsub($technician_commission, $store_money, 2) : $technician_commission;
      $technician_commission=$sub_commission?bcsub($technician_commission,$sub_commission,2):$technician_commission;
      $technician_commission=$first_level_commission?bcsub($technician_commission,$first_level_commission,2):$technician_commission;
      $order_sn = makePaySn($uid);
        $order_amount = bcadd($serve_price, $round_fare, 2);//服务费用加路费
        $order_zamount = bcsub($order_amount, $coupon_price, 2);//订单实际支付价
      $data = [
        'uid' => $uid,
        'address_id' => $address_id,
        'technician_id' => $technician_id,
        'store_id' => $technician['store_id'],
        'order_note' => $order_note,
        'serve_id' => $serve_id,
        'order_time' => time(),
        'quantity' => $quantity,
        'distance' => $round_mileage,
        'phone' => $phone,
        'order_status' => 0,
        'uname' => $uname,
        'gender' => $gender,
        'mileagefee' => $round_fare,
        'coupon_id' => $coupon_id,
        'createtime' => time(),
        'is_store_order' => 0,
        'store_money' => $store_money,
        'platform_money' => $platform_commission,
        'technician_price' => $technician_commission,
        'appointment_time' => $appointment_time,
        'serve_time' => $serve_time,
        'change_address' => 1,
         'book_start_time'=>$book_start_time,
        'book_end_time'=>$book_end_time,
        'u_address' => $uaddress,
        'coupon_money' => $coupon_price,
        'order_sn' => $order_sn,
        'first_level_commission' => $first_level_commission,
        'sub_commission' => $sub_commission,
        'order_amount' => $order_zamount,
        'order_amounts' => $order_amount,
        'lon'=>$lon,
        'lat'=>$lat,
        'detail'=>$udetail,
        'city'=>'',
        'serve_price'=>$serve_price
      ];
      $validate = Loader::validate('Order');
      if (!$validate->check($data)) {
        $this->error($validate->getError());
      }
      $osdata = [
        'serve_id' => $serve_id,
        'serve_name' => $serve->serve_name,
        'serve_image' => $serve->serve_image,
        'serve_duration' => $serve->serve_duration,
        'serve_price' => $serve->serve_price,
        'store_id' => $technician['store_id'],
        'store_name' => $store->name,
        'technician_id' => $technician_id,
        'technician_name' => $technician['technician_name'],
        'technician_avatar' => $technician['technician_avatar'],
        'technician_gender' => $technician['technician_gender'],
        'technician_phone'=>$technician['technician_phone'],
        'address_id' =>$address_id,
        'udetail' => $udetail,
        'uaddress' => $uaddress,
        'uphone' => $phone,
        'username' => $uname,
      ];
      adlog('订单信息', $data);
      $order_id = 0;
      Db::startTrans();
      try {
           $result=\app\common\model\Order::create($data);
        $osdata['order_id'] = $result->id;
        $order=OrderServe::create($osdata);
        $coupon=UseCoupon::where(['coupon_id'=>$coupon_id])->find();
        if($coupon){
          $coupon->use_time=time();
          $coupon->save();
        }
        Db::commit();
      } catch (PDOException $e) {
        Db::rollback();
        $this->error($e->getMessage());
      } catch (Exception $e) {
        Db::rollback();
        $this->error($e->getMessage());
      }
      if($result){
        $this->success('下单成功',$result);
      }else{
        $this->error('下单失败');
      }
    }


    /**
     * 支付订单
     * order_amount 订单支付价
     * order_id 订单id
     *
     */

    public function app_pay(){
        $uid=$this->auth->id;
        $order_id=$this->request->request('order_id');
       $type=$this->request->request('type');//支付方式 alipay=支付宝 wechat 微信  3 余额
       $userinfo=\app\common\model\User::get($uid);
       $orderinfo=\app\common\model\Order::where(['id'=>$order_id])->find();
        if(!$orderinfo){
            $this->error('订单信息错误');
        }
        if($orderinfo->uid!=$uid){
            $this->error('只能支付自己的订单');
        }
        if(!$orderinfo->order_amount || $orderinfo->order_amount < 0){
            $this->error("支付金额必须大于0");
        }
        if(!$type || !in_array($type, ['wechat', 'alipay',3])){

            $this->error("支付类型不能为空");
        }

        if($orderinfo->order_status != 0){
            $this->error('订单状态异常');
        }
        $orderinfo->save(['payment_type'=>$type]);
        if($type==3) {
            if ($userinfo['money'] < $orderinfo->order_amount) {
                $this->error('您当前的账户余额不足');
            }
            $serve = \app\admin\model\Serve::where(['id' => $orderinfo->serve_id])->find();
            if ($serve) {
                $memo = $serve->serve_name;
            } else {
                $memo = '';
            }
            Db::startTrans();
            try {
                \app\common\model\User::money($orderinfo->order_amount, $orderinfo->uid, $memo, 2, 1, 1);
                $serve = Serve::get($orderinfo->serve_id);
                $serve->save(['sales' => $serve['sales'] + 1]);
                $orderserve = OrderServe::where(['order_id' => $orderinfo->id])->find();
                if ($orderinfo['store_id'] != 0) {
                    $store = \app\admin\model\Store::where(['store_id' => $orderinfo['store_id']])->find();
                    if ($store) {
                        $store->sales = $store['sales'] + 1;
                        $store->save();
                    }
                    $tserve = TechnicianServe::where(['serve_id' => $serve->id, 'technician_id' => $orderserve->technician_id])->find();
                    if($tserve){
                        $tserve->sales =$tserve['sales'] + 1;
                        $tserve->save();
                    }
                }
                $technician = \app\admin\model\Technician::where(['technician_id' => $orderinfo->technician_id])->find();
                if($technician){
                    $technician->order_count = $technician['order_count'] + 1;
                    $technician->repurchase_num = $technician['repurchase_num'] + 1;
                    $technician->save();
                }
                $orderinfo->order_status = 1;
                $orderinfo->pay_time = time();
                $orderinfo->save();
                $amount               = Amount::get(1);
                $amount->income       = bcadd($amount->income,$orderinfo->order_amount,2);
                $amount->order_income = bcadd($amount->order_income,$orderinfo->order_amount,2);
                //给技师发短信
                $time = time();
                $technician_info = \app\admin\model\Technician::where('technician_id', $orderinfo['technician_id'])->find();
                $mobile          = \app\admin\model\User::where('id', $technician_info['uid'])->value('mobile');
                if( $technician_info['technician_phone'] ){
                    $mobile = $technician_info['technician_phone'];
                }
                if($mobile){
                    $res = \app\common\model\Sms::main($technician_info['technician_name'],$mobile,date('Y-m-d H:i:s',$time));
                    adlog('阿里短信', json_encode($res));
                    if($res->body->code == 'OK'){
                        $sms  = \app\common\model\Sms::create(['event' => 'new_old','mobile' => $mobile,'code' => $orderinfo['technician_id'],'ip' => '','createtime' => $time]);
                    }else{
                        adlog('新订单技师短信发送失败', json_encode($res));
                    }
                }
                Db::commit();
            }catch(Exception $e){
                Db::rollback();
                $this->error('支付失败');
            }
            $this->success('支付成功');
          }

        //订单号
        $out_trade_no = $orderinfo->order_sn;
        //订单标题
        $title = '用户订单';
        //回调链接
        $notifyurl = $this->request->root(true) . '/api/order/notifyx/paytype/' . $type . '/out_trade_no/' . $out_trade_no;
        $returnurl = $this->request->root(true) . '/api/order/returnx/paytype/' . $type . '/out_trade_no/' . $out_trade_no;
        $response = \addons\epay\library\Service::submitOrder($orderinfo->order_amount, $out_trade_no, $type, $title, $notifyurl, $returnurl, 'app');
        adlog('订单信息', $response);
        if($type == 'wechat'){
            $response = json_decode($response);
        }
        $this->success('', ['response' => $response]);
    }

  /**
   * 支付成功回调
   */

  public function notifyx(){

    $paytype = $this->request->param('paytype');
    $pay     = \addons\epay\library\Service::checkNotify($paytype);
    if(!$pay){
      echo '签名错误';
      return;
    }
    $data = $pay->verify();
    adlog('用户订单回调', $data);
    Db::startTrans();
    try{
      $out_trade_no = $data['out_trade_no'];
      $order=\app\admin\model\Order::where(['order_sn'=>$out_trade_no,'order_status'=>0])->find();
      if($order){
          $order->save(['order_status' => 1, 'pay_time' => time()]);
        $orderserve=OrderServe::where(['order_id'=>$order->id])->find();
        $serve=\app\admin\model\Serve::where(['id'=>$orderserve->id])->find();
        $serve->sales=$serve->sales+1;
        $serve->save();
        if($order->store_id!=0){
          $store=\app\admin\model\Store::where(['store_id'=>$order->store_id])->find();
          if($store){
            $store->sales = $store->sales + 1;
            $store->save();
          }
          $tserve=TechnicianServe::where(['serve_id'=>$serve->id,'technician_id'=>$orderserve->technician_id])->find();
          $tserve->sales = $tserve->sales + 1;
          $tserve->save();
        }
        $technician=\app\admin\model\Technician::where(['technician_id'=>$orderserve->technician_id])->find();
        $technician->order_count = $technician->order_count + 1;
        $technician->repurchase_num=$technician->repurchase_num+1;
        $technician->save();
        $amount               = Amount::get(1);
        $amount->income       = bcadd($amount->income,$order->order_amount,2);
        $amount->order_income = bcadd($amount->order_income,$order->order_amount,2);
        $amount->save();
        //给技师发短信
        $time = time();
        $technician_info = \app\admin\model\Technician::where('technician_id', '=',$order->technician_id)->find();
        $mobile          = \app\admin\model\User::where('id','=',$technician_info['uid'])->value('mobile');
        if( $technician_info['technician_phone'] ){
          $mobile = $technician_info['technician_phone'];
        }
        if($mobile){
          $res = \app\common\model\Sms::main($technician_info['technician_name'],$mobile,date('Y-m-d H:i:s',$time));
          adlog('阿里短信', json_encode($res));
          if($res->body->code == 'OK'){
            $sms  = \app\common\model\Sms::create(['event' => 'new_old','mobile' => $mobile,'code' => $order['technician_id'],'ip' => '','createtime' => $time]);
          }else{
            adlog('新订单技师短信发送失败', json_encode($res));
          }
        }
      }
      Db::commit();
    }catch(PDOException $e){
      Db::rollback();
      $this->error($e->getMessage());
    }catch(Exception $e){
      Db::rollback();
      $this->error($e->getMessage());
    }
    echo  $pay->success();
  }


  /**
   * @throws \think\db\exception\DataNotFoundException
   * @throws \think\db\exception\ModelNotFoundException
   * @throws \think\exception\DbException
   * 计算交通费
   */
  public function order_data()
  {
    $uid              = $this->auth->id;
    $address_id       = $this->request->request('address_id');
    $technician_id    = $this->request->request('technician_id');
      $serve_id    = $this->request->request('serve_id');
      $coupon_id    = $this->request->request('coupon_id');

    $appointment_time = $this->request->request('appointment_time');
    $address_info     = \app\common\model\Address::where('id', $address_id)->find();
    if(!$address_info){
        $lon=$this->request->request('lon');
        $lat=$this->request->request('lat');
    }else{
        $lon=$address_info->lon;
        $lat=$address_info->lat;
    }
    $technician_info  = \app\common\model\Technician::get($technician_id);
    $serve=Serve::where(['id'=>$serve_id,'serve_status'=>1,'is_added'=>0])->find();
    if(!$serve){
        $this->error('服务不存在');
    }
    $serve_price=$serve->serve_price;

    if($coupon_id){
        $coupon_price=Coupon::where(['id'=>$coupon_id,'status'=>1])->value('money');
        if(!$coupon_price){
           $coupon_price=0;
        }
    }else{
        $coupon_price=0;
    }

    if($lon && $lat){
      $distance= distance($lon, $lat, $technician_info['lon'], $technician_info['lat']);
    }else{
      $distance=distance($lon,$lat, $technician_info['lon'], $technician_info['lat']);
    }
    $appointment_time = date('H', strtotime($appointment_time));//获取是白天还是晚上
    $day_times        = config('site.day');   //白天
    $night_times      = config('site.night'); //晚上
    $mileage_cost     = 0;
    if($appointment_time >= $day_times && $appointment_time <= $night_times){
      if($distance > config('site.free_mileage')){
        $mileage_exceeded = $distance - config('site.free_mileage');//总里程-免费里程
        $mileage_cost     = bcmul($mileage_exceeded, config('site.kilometer_cost'), 2) * 2;//超出里程*里程单价  超出里程费用
      }else{
        $distance ;
      }
    }else{
      if($distance > config('site.free')){
        $mileage_exceeded = $distance - config('free');//总里程-免费里程
        $mileage_cost     = bcmul($mileage_exceeded, config('site.kilometer_nightcost'), 2) * 2;//超出里程*里程单价  超出里程费用
      }else{
        $distance;
      }
    }
    $zongjia=bcadd($mileage_cost, $serve_price,2)??0;
    $heji=bcsub($zongjia,$coupon_price,2)??0;
    $this->success('', ['mileage_cost' => $mileage_cost, 'distance' => $distance,'serve_price'=>$serve_price,'heji'=>$heji]);
  }




    /**
     * 订单评价
     */

    public function OrderComment(){
        $uid=$this->auth->id;
        $lon=$this->request->request('lon');
        $lat=$this->request->request('lat');
        $order_id=$this->request->request('order_id');
        $content=$this->request->request('content');
        $image=$this->request->request('image');
        $star=$this->request->request('star');
        if(!$star){
           $this->error('请输入分数');
        }
        if($star<0){
            $this->error('评价最低一星');
        }
        if($star==1){
            $type=3;
        }else if(in_array($star,[2,3,4])){
            $type=2;
        }else if($star==5){
          $type=1;
        }
   if(!$content){
    $this->error('请输入评价内容');
    }
        if($image){
            $type=4;
        }
        $address=Area::getCityFromLngLat($lon,$lat);
        $order=\app\common\model\Order::where(['id'=>$order_id,'uid'=>$uid])->find();
        if(!$order){
            $this->error('订单不存在');
        }
        if($order->order_status!=6){
          $this->error('当前订单未完成');
        }
        $technician_id=$order->technician_id;
        $technician=Technician::get($technician_id);
        $store_id=$technician['store_id'];
        $store=\app\common\model\Store::get($store_id);
        $serve_id=$order->serve_id;
        $serve=\app\common\model\Serve::get($serve_id);
        $data=[
            'uid'=>$uid,
            'address'=>$address->name,
            'store_id'=>$store_id,
            'serve_id'=>$serve_id,
            'content'=>$content,
            'star'=>$star,
            'type'=>$type,
            'image'=>$image,
             'order_id'=>$order_id,
          'createtime'=>time(),
            'technician_id'=>$technician_id
        ];
        $res=OrderComment::create($data);

        //技师好评率
        $technician['technician_fraction']=OrderComment::where(['technician_id'=>$technician_id])->group('technician_id')->avg('star');
        $technician['comment_count']=OrderComment::where(['technician_id'=>$technician_id])->count();
        $nice=OrderComment::where(['technician_id'=>$technician_id,'star'=>['>',4]])->count()?:0;
        $technician['feedback']=(bcdiv($nice,$technician['comment_count'],2)?:0).'%';
        //技师分数
        $star=OrderComment::where(['technician_id'=>$technician_id])->sum('star');
        $fraction=ceil($star /$technician['comment_count']);
        $technician['technician_fraction'] = $fraction;
        $technician['comprehensive_scoring']=bcadd($fraction,$technician['comprehensive_scoring'],2);
        $technician->save();
        //店铺好评率
        $store['store_grade']=OrderComment::where(['store_id'=>$store_id])->group('store_id')->avg('star');
        $comment=OrderComment::where(['store_id'=>$store_id])->count();
        $nicef=OrderComment::where(['store_id'=>$store_id,'star'=>['>',4]])->count()?:0;
        $store['feedback']=(bcdiv($nicef,$comment,2)?:0).'%';
        //店铺评分
        $stars=OrderComment::where(['store_id'=>$store_id])->sum('star');
         $store['store_grade'] = ceil($stars /$comment);
        $store->save();
        //服务的好评率
        $serve['star']=OrderComment::where(['serve_id'=>$serve_id])->group('serve_id')->avg('star');
        $ment=OrderComment::where(['serve_id'=>$serve_id])->count();
        $nicee=OrderComment::where(['serve_id'=>$serve_id,'star'=>['>',4]])->count()?:0;
        $serve['feedback']=(bcdiv($nicee,$ment,2)?:0).'%';
        //服务评分
        $stars=OrderComment::where(['serve_id'=>$serve])->sum('star');
        $serve['star'] = ceil($stars /$ment);
        $serve->save();
        $order->order_status=8;
        $order->comment_time=time();
        $order->save();
        if($res){
            $this->success('评论成功');
        }else{
            $this->error('评论失败');
        }
    }




    /**
     * 订单出发
     */

    public function start(){
        $uid=$this->auth->id;
        $order_id=$this->request->request('order_id');
        $order=\app\common\model\Order::where(['id'=>$order_id])->find();
        if(!$order){
            $this->error('订单不存在');
        }
        if(!in_array($order->order_status,[2,14])){
            $this->error('订单状态不为待服务，不可操作');
        }
        $order->order_status=3;
        $order->departure_time=time();
        $order->save();
        $this->success('成功');
    }



  /**
   * 技师接单
   */

  public function accept(){
    $uid=$this->auth->id;
    $postion=$this->auth->postion;
    $order_id=$this->request->request('order_id');
    $order=\app\common\model\Order::where(['id'=>$order_id])->find();
    if(!$order){
      $this->error('订单不存在');
    }
    if($postion!=2){
      $this->error('当前身份不是技师');
    }
    if($order->order_status!=1){
      $this->error('订单状态不为待接单，不可操作');
    }
    $technician=Technician::where(['technician_id'=>$order->technician_id])->find();
    if(!$technician){
      $this->error('找不到订单对应技师');
    }
      \app\common\model\User::money($order->technician_price,$uid,'技师完成订单增加余额',1,2,0);
      \app\common\model\User::money($order->mileagefee,$uid,'返路费',1,2,0);
      $order->order_status=2;
    $order->receiving_time=time();
    $order->save();
    $this->success('接单成功');
  }
    /**
     * 订单已到达
     */

    public function arrived(){
        $uid=$this->auth->id;
        $order_id=$this->request->request('order_id');
        $order=\app\common\model\Order::where(['id'=>$order_id])->find();
        if(!$order){
            $this->error('订单不存在');
        }
        if($order->order_status!=3){
            $this->error('订单状态不为已出发，不可操作');
        }
        $order->order_status=4;
        $order->arrive_time=time();
        $order->save();
        $this->success('成功');
    }

    /**
     * 订单开始服务
     */

    public function beginServe(){
        $uid=$this->auth->id;
        $order_id=$this->request->request('order_id');
        $order=\app\common\model\Order::where(['id'=>$order_id,'uid'=>$uid])->find();
        if(!$order){
            $this->error('订单不存在');
        }
        if($order->order_status!=4){
            $this->error('订单状态不为已到达，不可操作');
        }
        $order->order_status=5;
        $order->beginserve_time=time();
        $order->save();
        $this->success('成功');
    }

  /**
   * 订单完成
   */

  public function finish_order()
  {
    $uid = $this->auth->id;
    $order_id = $this->request->request('order_id');
    $order = \app\common\model\Order::where(['id' => $order_id])->find();
//    if ($order->order_status !=5) {
//      $this->error('订单状态异常');
//    }
      if(!in_array($order->order_status,[5,14])){
          $this->error('订单状态异常');
      }
    $technician_id = $order->technician_id;
    $technician = Technician::where(['technician_id' => $technician_id])->find();
    $user=\app\admin\model\User::where(['id'=>$technician->uid,'del_flag'=>0])->find();
    $money=bcadd($order->technician_price,$order->mileagefee,2);
    $after=function_exists('bcadd') ? bcadd($user->money, $money, 2) : $user->money + $money;
    $res=MoneyLog::where(['user_id' =>$technician->uid, 'postion' => 2, 'is_clearing' => 0])->update(['is_clearing' => 1,'after'=>$after]);
    if($res){
      $uinfo=User::where(['id'=>$technician->uid])->find();
      $uinfo->money=$after;
      $uinfo->save();
    }
    Db::startTrans();
    try {
        if($order->plusitem_money!=0){
            $orderserve=OrderServe::get(['order_id'=>$order->id]);
            $orderserve->sales=$orderserve['sales']+1;
            $orderserve->save();
            $serve=Serve::where(['id'=>$orderserve['plusitem_serve_id']])->find();
            $serve->sales=$serve->sales+1;
            $serve->save();
            $tserve=TechnicianServe::where(['serve_id'=>$orderserve['plusitem_serve_id'],'technician_id'=>$technician->technician_id])->find();
            if($tserve){
                $tserve->sales=$tserve->sales+1;
                $tserve->save();
            }
            if($technician->store_id != 0){
                $store = \app\common\model\Store::where(['store_id' => $technician->store_id])->find();
                $store->sales=$store->sales+1;
                $store->save();
            }
            $technician->order_count=$technician->order_count+1;
            $technician->turnover=$technician->turnover+1;
            $technician->save();
        }
      if ($technician->store_id != 0) {
        $store = \app\common\model\Store::where(['store_id' => $technician->store_id])->find();
        \app\common\model\User::money($order->store_money, $store->uid, '技师完成订单增加店铺余额', 1, 3, 1);
        $store_user = \app\admin\model\User::where(['id' => $store->uid, 'del_flag' => 0])->find();
        $store_data = [
          'store_id' => $store->store_id,
          'uid' => $store->uid,
          'money' => $order->store_money??0,
          'createtime' => time(),
          'order_sn' => $order->order_sn,
          'before' => $store_user->money??0,
          'after' => bcadd($store_user->money, $order->store_money, 2),
          'note' => '店铺技师完成订单增加商家余额'
        ];
        StoreMoneyLog::create($store_data);
        $order_count=\app\admin\model\Order::where(['store_id'=>$store->store_id,'order_status'=>['in',[2,3,4,5]]])->count()?:0;
        if($order_count<=0){
            $order_count=1;
        }
        $sales=0;//初始化服务数量
        if($store->sales<=0){
            $sales=1;
        }
        $feedback=(bcdiv($order_count?:1,$sales?:1,2)?:0).'%';
        $store->order_rate=$feedback;
        $store->save();
      }
      //增加平台余额
      if ($order->platform_money != 0) {
        $log = [
          'order_id' => $order_id,
          'money' => $order->platform_money,
          'createtime' => time()
        ];
        PlatForm::create($log);
      }
      $addclock=Addclock::where(['order_id'=>$order->id])->sum('price');
      if($order->technician_price!=0){
          $price=bcsub($order->technician_price,$addclock,2);
          User::money($price,$order->technician_id,'加钟订单技师收益',1,2,1);
      }
      $user = \app\admin\model\User::where(['id' => $uid])->find();
      //增加上级收益
      if ($order->sub_commission != 0) {
        $parent = \app\admin\model\User::where('id', $user->inviter_id)->find();
        if ($parent) {
          $parentlog = [
            'uid' => $order->uid,
            'createtime' => time(),
            'pid' => $parent->id,
            'pprice' => $order->sub_commission,
            'order_money' => $order->order_amount,
            'order_sn' => $order->order_sn,
            'note' => '上级用户分成',
            'uprice' => $order->order_amounts
          ];
          $res = ParentMoneyLog::create($parentlog);
          if ($res) {
            \app\common\model\User::money($order->sub_commission, $parent->id, '下级用户下单提成', 1, 1, 1);
          }
        }
        //增加上上级收益
        if ($order->first_level_commission != 0) {
          $p_parent = \app\common\model\User::where(['id' => $parent->inviter_id])->find();
          if ($p_parent) {
            $res = ParentMoneyLog::create([
              'uid' => $order->uid,
              'uprice' => $order->order_amount,
              'pid' => $p_parent->id,
              'pprice' => $order->first_level_commission,
              'order_money' => $order->order_amounts,
              'order_sn' => $order->order_sn,
              'note' => '上上级用户分成',
              'createtime' => time()
            ]);
            if ($res) {
              \app\common\model\User::money($order->first_level_commission, $p_parent->id, '下下级用户下单提成', 1, 1, 1);
            }
          }
        }
      }
      $order->order_status = 6;
      $order->endserve_time = time();
      $order->save();
    }catch (Exception $e){
      Db::rollback();
      $this->error($e->getMessage());
    }
    Db::commit();
    $this->success('完成成功');
  }


    /**
     * 技师订单列表
     */
    public function technician_orderlist(){
      $uid        = $this->auth->id;
      $type       = $this->request->request('type');//1 新订单 2 进行中 3 已完成
        $page=$this->request->request('page',1);
      $technician = Technician::where('uid','=', $uid)->find();
      if($type == 1){
        $where['order_status'] = ['in', [1]];
      }else if($type == 2){
        $where['order_status'] = ['in', [2,3,4,5]];
      }else if($type == 3){
        $where['order_status'] = ['in', [6,8]];
      }
      $where['technician_id']=$technician['technician_id'];
      $orderlist = \app\common\model\Order::where($where)->page($page,10)->order('createtime','desc')->field('id,serve_id,store_id,technician_id,serve_time,order_status,appointment_time')->select();
      foreach ($orderlist as $v){
        $v['store']=\app\common\model\Store::where(['store_id'=>$v['store_id']])->field('store_id,name')->find();
        $serve=\app\common\model\Serve::where(['id'=>$v['serve_id']])->field('serve_image,serve_name,serve_price,id')->find();
        $v['serve_price']=$serve['serve_price'];
        $v['serve_name']=$serve['serve_name'];
        $v['serve_image']=$serve['serve_image'];
      }
      $this->success('', $orderlist??[]);
    }


  /**
   * 商家代客下单
   */

  public function replaceOrder()
  {
    $uid = $this->auth->id;
    $phone = $this->request->request('phone');//客户电话
    $address = $this->request->request('address');//客户地址
    $technician_id = $this->request->request('technician_id');//技师id
    $detail = $this->request->request('detail');//客户地址详情
    $appointment_time = $this->request->request('appointment_time');//预约时间
    $serve_id = $this->request->request('serve_id');//服务id
    $order_note = $this->request->request('order_note', '');//订单备注
    $city = $this->request->request('city');//城市
    $lon = $this->request->request('lon');//经度
    $lat = $this->request->request('lat');//纬度
    $gender= $this->request->request('gender');//性别
    $uname= $this->request->request('uname');//下单人姓名
    $quantity = $this->request->request('quantity');//服务数量
    $coupon_id = $this->request->request('coupon_id');//优惠券id
    if ($phone) {
      $userinfo = \app\admin\model\User::where(['mobile' =>$phone, 'postion' => 1])->find();
      if(!$userinfo){
          $this->error('当前用户不存在');
      }
    }
    $serve = \app\admin\model\Serve::where(['id' => $serve_id])->find();
    $technician = Technician::get($technician_id);
    $store = \app\common\model\Store::where(['uid' => $uid])->find();
    $serve_time = $serve->serve_duration * $quantity;
    $serve_price = $serve->serve_price;
    $order_amount = bcmul($serve_price, $quantity, 2);//订单原价

    if (!$technician) {
      $this->error('该技师不存在');
    }
    if ($technician['store_id'] == 0) {
      $this->error('该技师还未加入店铺');
    }
    $day=datetime($appointment_time,'w');

    $technicians=Technician::where(['work_day'=>['like',"%$day%"]])->find();
    if(!$technicians){
      $this->error('当前不在技师工作日内');
    }

    $tserve=TechnicianServe::where(['technician_id'=>$technician_id,'serve_id'=>$serve_id])->find();
    if(!$tserve){
      $this->error('该技师没有该服务');
    }
    if(!$technician['serve_time']&&!$technician['serve_time_end']){
      $this->error('该技师暂未上传工作时间');
    }
    $book_start_time=strtotime($appointment_time);
    $book_end_time=$book_start_time+$serve_time*60;
    if ($coupon_id) {
      $coupon_info = UseCoupon::where(['coupon_id' => $coupon_id])->find();
      $coupon_money = Coupon::where(['id' => $coupon_info['coupon_id']])->value('term');
      if ($order_amount >= $coupon_money) {
        $coupon_price = Coupon::where(['id' => $coupon_info['coupon_id']])->value('money');
      } else {
        $coupon_price = 0;
      }
    } else {
      $coupon_price = 0;
    }
    $roundinfo = $this->get_order_distance($lon, $lat,$technician_id, $appointment_time);//路程信息
    $round_mileage = $roundinfo['distance']; //里程
    $round_fare = $roundinfo['mileage_cost'];//里程价格

    if ($round_mileage['distance'] > 50) {
      $this->error('距离过远,请联系平台客服');
    }
    $inviteinfo = Invitelog::where('Invitees', $userinfo['id'])->find();
    $first_level_commission = 0;
    $sub_commission = 0;
    if (isset($inviteinfo['Invitee'])) {
      //上级用户信息
      $last_userinfo = \app\common\model\User::get($inviteinfo['Invitee']);//上级用户信息
      $sub_commission = bcmul($order_amount, config('site.sub_commission') / 100, 2);//上级分佣
      $twoinfo = Invitelog::where('Invitees', $last_userinfo->id)->find();
      if ($twoinfo) {
        $twolast_info = \app\common\model\User::get($twoinfo['Invitee']);//上上级用户信息
        if ($twolast_info) {
          $first_level_commission = bcmul($order_amount, config('site.first_level_commission') / 100, 2);//上上级分佣
        } else {
          $first_level_commission = 0;
        }
      }
    } else {
      $sub_commission = 0;
    }
    //平台抽成
    $platform_commission = bcmul($order_amount, config('site.platform_commission') / 100, 2);

    //店铺分佣
    if ($technician['store_id'] != 0 && $technician['is_join_store'] == 1) {
      $store_money = bcmul($order_amount, config('site.store_commission') / 100, 2);
    } else {
      $store_money = 0;
    }
    //技师分佣
    $technician_commission = bcsub($order_amount, $platform_commission, 2);//技师分佣
    $technician_commission = $store_money ? bcsub($technician_commission, $store_money, 2) : $technician_commission;
      $technician_commission=$sub_commission?bcsub($technician_commission,$sub_commission,2):$technician_commission;
      $technician_commission=$first_level_commission?bcsub($technician_commission,$first_level_commission,2):$technician_commission;
    $order_sn = makePaySn($userinfo['id']);
      $order_amount = bcadd($order_amount, $round_fare, 2);//服务费用加路费
      $order_zamount = bcsub($order_amount, $coupon_price, 2);//订单实际支付价
    $data = [
      'uid' => $userinfo['id'],
      'lon' => $lon,
      'address_id'=>0,
      'lat' => $lat,
      'city' => $city,
      'order_note' => $order_note,
      'serve_id' => $serve_id,
      'appointment_time' => $appointment_time,
      'detail' => $address,
      'serve_price' => $serve->serve_price,
      'is_store_order' => 1,
      'order_time' => time(),
      'createtime' => time(),
       'book_start_time'=>$book_start_time,
      'book_end_time'=>$book_end_time,
      'technician_id' => $technician_id,
      'phone' => $phone,
      'u_address' => $detail,
      'store_id'=>$store->store_id,
      'coupon_id'=>$coupon_id,
      'coupon_money'=>$coupon_price,
      'order_sn'=>$order_sn,
      'technician_price'=>$technician_commission,
      'store_money'=>$store_money,
      'platform_money'=>$platform_commission,
      'first_level_commission'=>$first_level_commission,
      'sub_commission'=>$sub_commission,
      'order_amount'=>$order_zamount,
      'order_amounts'=>$order_amount,
       'gender'=>$gender,
       'uname'=>$uname,
      'distance'=>$round_mileage,
      'mileagefee'=>$round_fare,
      'order_status'=>0,
      'change_address'=>1,
      'serve_time'=>$serve_time,
      'quantity'=>$quantity
    ];
    $osdata = [
      'serve_id' => $serve_id,
      'serve_name' => $serve->serve_name,
      'serve_image' => $serve->serve_image,
      'serve_duration' => $serve->serve_duration,
      'serve_price' => $serve->serve_price,
      'store_id' => $store->store_id,
      'store_name' => $store->name,
      'technician_id' => $technician_id,
      'technician_name' => $technician['technician_name'],
      'technician_avatar' => $technician['technician_avatar'],
      'technician_gender' => $technician['technician_gender'],
      'technician_phone'=>$technician['technician_phone'],
      'address_id' => 0,
      'udetail' => $address,
      'uaddress' =>$detail,
      'uphone' => $phone,
      'username' =>$uname,
    ];
    adlog('订单信息', $data);
    $order_id = 0;
    Db::startTrans();
    try {
      $result=\app\common\model\Order::create($data);
      $osdata['order_id'] = $result->id;
      $order=OrderServe::create($osdata);
      $coupon=UseCoupon::where(['coupon_id'=>$coupon_id])->find();
      if($coupon){
        $coupon->use_time=time();
        $coupon->save();
      }
      Db::commit();
    } catch (PDOException $e) {
      Db::rollback();
      $this->error($e->getMessage());
    } catch (Exception $e) {
      Db::rollback();
      $this->error($e->getMessage());
    }
    if($result){
      $this->success('下单成功',$result);
    }else{
      $this->error('下单失败');
    }
  }

  /**
   * 订单交通费
   */

  public function get_order_distance($lon,$lat,$technician_id ,$appointment_time){
    $technician=Technician::where(['technician_id'=>$technician_id])->find();
    $distance         = distance($lon, $lat, $technician->lon, $technician->lat);
    $appointment_time = date('H', strtotime($appointment_time));//获取是白天还是晚上
    $day_times        = config('site.day');   //白天
    $night_times      = config('site.night'); //晚上
    $mileage_cost     = 0;
    if($appointment_time >= $day_times && $appointment_time <= $night_times){
      if($distance > config('site.free_mileage')){
        $mileage_exceeded = $distance - config('site.free_mileage');//总里程-免费里程
        $mileage_cost     = bcmul($mileage_exceeded, config('site.kilometer_cost'), 2) * 2;//超出里程*里程单价  超出里程费用
      }else{
        $distance ;
      }
    }else{
      if($distance > config('site.free')){
        $mileage_exceeded = $distance - config('free');//总里程-免费里程
        $mileage_cost     = bcmul($mileage_exceeded, config('site.kilometer_nightcost'), 2) * 2;//超出里程*里程单价  超出里程费用
      }else{
        $distance;
      }
    }
    return ['mileage_cost' =>  $mileage_cost, 'distance' => $distance];
  }



  /**
   * 商家端订单列表
   * type 1 进行中 2 已完成
   */

  public function store_orderlist(){
    $uid=$this->auth->id;
    $type=$this->request->request('type');
    $page=$this->request->request('page',1);
    $store=\app\common\model\Store::where(['uid'=>$uid])->find();
    if($type==1){
      $where['order_status']  = ['IN', [2,3,4,5,14]];
    }else if($type==2){
      $where['order_status']  = ['IN', [6]];
    }else{
      $where=[];
    }
    $where['store_id']=$store->store_id;
    $orderlist=\app\common\model\Order::where($where)->page($page,10)->order('createtime','desc')->field('id,serve_id,store_id,technician_id,appointment_time,order_status,detail,u_address,order_time,pay_time,order_note,address_id')->select();
    foreach ( $orderlist as $k=>$v){
      $serve=\app\common\model\Serve::where(['id'=>$v['serve_id']])->field('serve_image,serve_name,serve_price,id,serve_type')->find();
      $v['serve_price']=$serve['serve_price'];
      $v['serve_name']=$serve['serve_name'];
      $v['serve_image']=$serve['serve_image'];
        $v['serve_type']=$serve['serve_type'];
        $v['order_time']=date('Y-m-d H:i',$v['order_time']);
    }
    $this->success('',$orderlist??[]);

  }


  /**
   * 订单搜索
   */


  public function Orderfind(){
    $uid=$this->auth->id;
    $store=\app\common\model\Store::where(['uid'=>$uid])->find();
      $type=$this->request->request('type');
    $city=$this->request->request('city');//城市
    $technician_name=$this->request->request('technician_name');//技师名称
    $technician_phone=$this->request->request('technician_phone');//技师电话
    $nickname=$this->request->request('nickname');//昵称
    $phone=$this->request->request('phone');//电话
    $serve_name=$this->request->request('serve_name');//服务名称
    $order_sn=$this->request->request('order_sn');//订单编号
    $order_time=$this->request->request('order_time');
    $order_times=$this->request->request('order_times');
    $page=$this->request->request('page',1);
    $appointment_time=$this->request->request('appointment_time');//预约时间
    $appointment_times=$this->request->request('appointment_times');//预约时间

     $where=[];
     $wheress=[];
     $where['store_id']=$store->store_id;
     if($order_sn){
       $wheres['order_sn']=$order_sn;
     }
      if($type==1){
          $where['order_status']  = ['IN', [2,3,4,5,14]];
      }else if($type==2){
          $where['order_status']  = ['IN', [6]];
      }else{
          $where=[];
      }
     if($order_time ||$order_times){
       $where['order_time']=["between time",[$order_time,$order_times]];
     }
     if($appointment_time&&$appointment_times){
       $where['appointment_time']=["between time",[$appointment_time,$appointment_times]];
     }
     if($city){
       $where['city']=['like',"%$city%"];
     }
     if($phone){
       $where['phone']=$phone;
     }
     if($nickname){
       $where['uname']=$nickname;
     }
     if($serve_name){
       $serves=\app\common\model\Serve::where(['serve_name'=>$serve_name])->group('id')->column('id');
       if($serves){
         $where['serve_id']=['in',$serves];
       }
     }
     if($technician_name){
       $wheres['technician_name']=['like',"%$technician_name%"];
       $technician_id=Technician::where($wheres)->group('technician_id')->column('technician_id');
       if($technician_id){
         $where['technician_id']=['in',$technician_id];
       }
     }
    if($technician_phone){
      $wheres['technician_phone']=$technician_phone;
      $technician_id=Technician::where($wheres)->group('technician_id')->column('technician_id');
      if($technician_id){
        $where['technician_id']=['in',$technician_id];
      }
    }
    $orderlist=\app\common\model\Order::where($where)->where($wheress)->page($page,10)->order('createtime','desc')->field('id,serve_id,store_id,technician_id,appointment_time,order_status,detail,u_address,order_time,pay_time,order_note,address_id,order_sn')->select();
    foreach ( $orderlist as $k=>$v){
      $serve=\app\common\model\Serve::where(['id'=>$v['serve_id']])->field('serve_image,serve_name,serve_price,id')->find();
      $v['serve_price']=$serve['serve_price'];
      $v['serve_name']=$serve['serve_name'];
      $v['serve_image']=$serve['serve_image'];
      $v['order_time']=date('Y-m-d H:i',$v['order_time']);
      if($v['pay_time']){
        $v['pay_time']=date('Y-m-d H:i',$v['pay_time']);
      }else{
        $v['pay_time']=0;
      }

    }
    $this->success('',$orderlist);
  }


  /**
   * 催单
   */

  public function Reminder(){

    $order_id=$this->request->request('order_id');
    $time = time();
    $uid=$this->auth->id;
    $orderinfo    = \app\common\model\Order::where(['id'=>$order_id,'order_status' => 1])->find();
    if(!$orderinfo){
      $this->error('订单不存在');
    }
      $urgeTime = config('site.urge');//催单间隔时间
      $urgeMax = config('site.urge_max'); // 催单最大次数
      $urge = Urge::all(['order_id' => $order_id]);
      $times = $urgeTime * 60;
     if($urge){
         $count = count($urge);
         if($count >= $urgeMax){
             $this->error('已到催单最大次数');
         }
         $urgeLog = Urge::where(['order_id' => $order_id])->order('log_time desc')->find();
         if($urgeLog){
             $urgeTime = $times + $urgeLog->log_time;
             if($urgeTime < time()){
                 $technician_info = \app\admin\model\Technician::where('technician_id', $orderinfo['technician_id'])->find();
                 $mobile          = \app\admin\model\User::where('id', $technician_info['uid'])->value('mobile');
                 if($technician_info['technician_phone'] ){
                     $mobile = $technician_info['technician_phone'];
                 }
                 if($mobile){
                     $result = Urge::create(['order_id' => $order_id, 'uid' => $uid,'log_time'=>$time]);
                     $res = \app\common\model\Sms::main($technician_info['technician_name'],$mobile,date('Y-m-d H:i:s',$time));
                     adlog('阿里短信', json_encode($res));
                     if($res->body->code == 'OK'){
                         $sms  = \app\common\model\Sms::create(['event' => 'new_old','mobile' => $mobile,'code' => $orderinfo['technician_id'],'ip' => '','createtime' => $time]);
                     }else{
                         adlog('新订单技师短信发送失败', json_encode($res));
                     }
                     if($result){
                         $this->success('催单成功');
                     }else{
                         $this->error('催单失败');
                     }
                 }
             }else{
                 $this->error('催单频繁');
             }
         }
     }else{
         $technician_info = \app\admin\model\Technician::where('technician_id', $orderinfo['technician_id'])->find();
         $mobile          = \app\admin\model\User::where('id', $technician_info['uid'])->value('mobile');
         if($technician_info['technician_phone'] ){
             $mobile = $technician_info['technician_phone'];
         }
         if($mobile){
             $result = Urge::create(['order_id' => $order_id, 'uid' => $uid,'log_time'=>$time]);
             $res = \app\common\model\Sms::main($technician_info['technician_name'],$mobile,date('Y-m-d H:i:s',$time));
             adlog('阿里短信', json_encode($res));
             if($res->body->code == 'OK'){
                 $sms  = \app\common\model\Sms::create(['event' => 'new_old','mobile' => $mobile,'code' => $orderinfo['technician_id'],'ip' => '','createtime' => $time]);
             }else{
                 adlog('新订单技师短信发送失败', json_encode($res));
             }
             if($result){
                 $this->success('催单成功');
             }else{
                 $this->error('催单失败');
             }
         }
     }
  }


  /**
   * 技师拒绝接单
   */

  public function refuse_order()
  {
    $time=time();
    $order_id = $this->request->request('order_id');
    $order = \app\common\model\Order::where(['id' => $order_id])->find();
    if (!$order) {
      $this->error('订单不存在');
    }
    if ($order->order_status != 1) {
      $this->error('当前订单不为待接单，不可操作');
    }
    $technician = Technician::where(['technician_id' => $order->technician_id])->find();
    if (!$technician) {
      $this->error('未找到订单对应技师');
    }
    if ($order->pay_time != 0) {
      if ($order->payment_type == 3) {
        \app\common\model\User::money($order->order_amount, $order->uid, '技师拒绝接单退款', 1, 1, 1);
      } else {
        $result = Pay::refund($order, '技师拒绝接单退款', $order->order_amount);
        if (!$result) {
          $this->error('付款原路退回出错');
        }
      }
    }
    $mobile =$order->phone;
    if ($mobile) {
      $res = \app\common\model\Sms::refund_sms($order->uname, $mobile, date('Y-m-d H:i:s', $time));
      adlog('阿里短信', json_encode($res));
      if ($res->body->code == 'OK') {
        $sms = \app\common\model\Sms::create(['event' => 'refuse_order', 'mobile' => $mobile, 'code' => $order['technician_id'], 'ip' => '', 'createtime' => $time]);
      } else {
        adlog('技师拒绝订单短信发送失败', json_encode($res));
      }
    }
    $order->order_status = 10;
    $order->save();
    $this->success('拒绝成功');
  }


  /**
   * 订单补差价支付
   */

  public function platform_order(){
    $uid=$this->auth->id;
    $serve_id=$this->request->request('serve_id');
    $pay_type = $this->request->request('pay_type');
    $order_id=$this->request->request('order_id');
    $userinfo=\app\admin\model\User::where(['id'=>$uid])->find();
    $order=\app\admin\model\Order::get(['id'=>$order_id]);
    $serve=Serve::where(['id'=>$serve_id])->find();
    if(!$order){
      $this->error('订单不存在');
    }
      $money =$serve->serve_price;
    if(!$serve){
        $this->error('要加钟的服务不存在');
    }
//    if($order->order_status!=2){
//      $this->error('订单状态不为待服务');
//    }
      $out_trade_no=makePaySn($uid);
      if (!$pay_type || !in_array($pay_type, ['wechat', 'alipay',3])) {

          $this->error('支付方式错误');
      }

    if($pay_type==3) {
        if ($userinfo->money < $money) {
            $this->error('余额不足');
        }
        Db::startTrans();
        try {
            User::money($money, $uid, '用户余额加钟支付', 2, 1, 1);
            $orderserve = OrderServe::where(['order_id' => $order_id])->find();
            $commissions = $this->commission($money, $order->technician_id, $uid);
            $store_money       = $commissions['store_commission']; //店铺分佣
            $technician_commission  = $commissions['technician_commission']; //技师分佣
            $platform_commission    = $commissions['platform_commission']; //平台分佣
            $first_level_commission = $commissions['first_level_commission'];//二级分佣
            $sub_commission         = $commissions['sub_commission'];//一级分佣
            $orderserve->plusitem_serve_id = $serve_id;
            $orderserve->save();
            $data=[
                'order_id'=>$order_id,
                'uid'=>$uid,
                'serve_id'=>$serve_id,
                'price'=>$money,
                'order_sn'=>$out_trade_no,
                'createtime'=>time(),
                'status'=>1,
                'pay_type'=>$pay_type,
                 'pay_time'=>time(),
                'technician_id'=>$order->technician_id
            ];
            Addclock::create($data);
            $order->order_status = 14;
            $order->add_bell_time = time();
            $order->technician_price = bcadd($order['technician_price'], $technician_commission, 2);
            $order->platform_money = bcadd($order['platform_money'], $platform_commission, 2);
            $order->store_money = bcadd($order['store_money'], $store_money, 2);
            $order->sub_commission = bcadd($order['sub_commission'], $sub_commission, 2);
            $order->first_level_commission = bcadd($order['first_level_commission'], $first_level_commission, 2);
            $order->save();
            Db::commit();
        } catch (\think\exception\PDOException $e) {
            Db::rollback();
            $this->error('支付失败');
        }
        $this->success('支付成功');
    }else {
        $orderserve = OrderServe::where(['order_id' => $order_id])->find();
        $commissions = $this->commission($money, $order->technician_id, $uid);
        $store_money       = $commissions['store_commission']; //店铺分佣
        $technician_commission  = $commissions['technician_commission']; //技师分佣
        $platform_commission    = $commissions['platform_commission']; //平台分佣
        $first_level_commission = $commissions['first_level_commission'];//二级分佣
        $sub_commission         = $commissions['sub_commission'];//一级分佣
        $orderserve->plusitem_serve_id = $serve_id;
        $orderserve->save();
        $data=[
            'order_id'=>$order_id,
            'uid'=>$uid,
            'serve_id'=>$serve_id,
            'price'=>$money,
            'order_sn'=>$out_trade_no,
            'createtime'=>time(),
            'status'=>0,
            'pay_type'=>$pay_type,
            'technician_id'=>$order->technician_id
        ];
        Addclock::create($data);
//        $order->plusitem_money = $money;
        $order->technician_price = bcadd($order['technician_price'], $technician_commission, 2);
        $order->platform_money = bcadd($order['platform_money'], $platform_commission, 2);
        $order->store_money = bcadd($order['store_money'], $store_money, 2);
        $order->sub_commission = bcadd($order['sub_commission'], $sub_commission, 2);
        $order->first_level_commission = bcadd($order['first_level_commission'], $first_level_commission, 2);
        $order->save();
        $title = '用户补差价支付';
        $notifyurl = $this->request->root(true) . '/api/order/gnotifyx/paytype/' . $pay_type . '/out_trade_no/' . $out_trade_no;
        $returnurl = $this->request->root(true) . '/api/order/returnx/paytype/' . $pay_type . '/out_trade_no/' . $out_trade_no;
        $response = \addons\epay\library\Service::submitOrder($money, $out_trade_no, $pay_type, $title, $notifyurl, $returnurl, 'app');
        adlog('用户补差价支付参数', $response);
        if ($pay_type == 'wechat') {
            $response = json_decode($response);
        }
        $this->success('', ['response' => $response]);
    }
  }


    /**
     * 分佣
     */

    /**
     * @return array
     */
    public function commission($order_amount, $technician_id, $uid)
    {

        $inviteinfo             = \app\admin\model\User::where('id',$uid)->find();
        $technician       = \app\common\model\Technician::where('technician_id', $technician_id)->find();
        $first_level_commission = 0;
        $sub_commission = 0;
        if($inviteinfo&&$inviteinfo['inviter_id']){
            $last_userinfo = \app\common\model\User::get($inviteinfo['inviter_id']);//上级用户信息
            if ($last_userinfo) {
                $sub_commission = bcmul($order_amount, config('site.sub_commission') / 100, 2);//上级分佣
                $twoinfo = \app\admin\model\User::where('id', $last_userinfo['inviter_id'])->find(); //根据上级ID查询上上级ID
                if ($twoinfo) {
                    $twolast_info = \app\common\model\User::get($twoinfo['id']);//上上级用户信息
                    if ($twolast_info) {
                        $first_level_commission = bcmul($order_amount, config('site.first_level_commission') / 100, 2);//上上级分佣
                    } else {
                        $first_level_commission = 0;
                    }
                }
            } else {
                $sub_commission = 0;
            }
        }
        //平台抽成
        $platform_commission = bcmul($order_amount, config('site.platform_commission') / 100, 2);

        //店铺分佣
        if ($technician['store_id'] != 0 && $technician['is_join_store'] == 1) {
            $store_money = bcmul($order_amount, config('site.store_commission') / 100, 2);
        } else {
            $store_money = 0;
        }
        //技师分佣
        $technician_commission = bcsub($order_amount, $platform_commission, 2);//技师分佣
        $technician_commission = $store_money ? bcsub($technician_commission, $store_money, 2) : $technician_commission;
        $technician_commission=$sub_commission?bcsub($technician_commission,$sub_commission,2):$technician_commission;
        $technician_commission=$first_level_commission?bcsub($technician_commission,$first_level_commission,2):$technician_commission;
        return [
            'platform_commission'    => $platform_commission,
            'technician_commission'  => $technician_commission,
            'store_commission'       => $store_money,
            'first_level_commission' => $first_level_commission,
            'sub_commission'         => $sub_commission
        ];

    }




  /**
   * 支付成功回调
   */

  public function gnotifyx()
  {
    $paytype = $this->request->param('paytype');
    adlog('支付方式', $paytype);
    $pay = \addons\epay\library\Service::checkNotify($paytype);
    if (!$pay) {
      echo '签名错误';
      return;
    }
    $data = $pay->verify();
    adlog('用户补差价回调', $data);
    Db::startTrans();
    try {
      $out_trade_no = $data['out_trade_no'];
        adlog('加钟补差价', $out_trade_no);
        $order = Addclock::get(['order_sn' =>$out_trade_no,'status'=>0]);
        if($order){
            dump(111);
            $order->status=1;
            $order->pay_time=time();
            $order->save();
            $orders=\app\common\model\Order::where(['id'=>$order['order_id']])->find();
            $orders->order_status = 14;
            $orders->add_bell_time = time();

            $orders->save();
        }
      Db::commit();
    } catch (\think\exception\PDOException $e) {
      Db::rollback();
      $this->error($e->getMessage());
    } catch (\http\Exception $e) {
      Db::rollback();
      $this->error($e->getMessage());
    }
      echo  $pay->success()->getContent();
  }

    /**
     * 支付返回，仅供开发测试
     */
    public function returnx()
    {
        $paytype      = $this->request->param('paytype');
        $out_trade_no = $this->request->param('out_trade_no');
        $pay          = Service::checkReturn($paytype);
        if (!$pay) {
            $this->error('签名错误','');
        }

        //你可以在这里通过out_trade_no去验证订单状态
        //但是不可以在此编写订单逻辑！！！

        $this->success("请返回网站查看支付结果",addon_url("epay/index/index"));
    }

  /**
   * 获取订单时间段技师是否有其他订单
   */
  public function isExistTime()
  {
    $tid  = $this->request->request('tid');
    $time = $this->request->request('time');

    $order = Db::name('order_serve')
      ->alias('os')
      ->join('order o','o.id=os.order_id')
      ->where(['o.appointment_time' => $time,'os.technician_id' => $tid])
      ->find();
    if ($order) {
      $this->error('该技师此时间段可能有其他订单, 请谨慎选择.');
    } else {
      $this->success('请求成功');
    }
  }

  /*
   * 获取当前预约时间下技师列表
   */

  public function time_technicianlist(){

      $uid=$this->auth->id;
      $store=\app\admin\model\Store::where(['uid'=>$uid])->find();
    $lon=$this->request->request('lon');
    $lat=$this->request->request('lat');
    $time=$this->request->request('time');
    $times = strtotime($time);
    $timey=datetime($times,'H:i');
    $week = date('w', $times);
    $where=[];
    if($week){
        $where['work_day']=['like',"%$week%"];
    }
    if($store){
        $where['store_id']=['in',$store->store_id];
    }

     $info=Technician::where($where)->field('technician_id,technician_avatar,lon,lat,serve_time,serve_time_end')->select();
     if($info){
     $technician=Technician::where('serve_time','<',$timey)->where('serve_time_end','>=',$timey)->field('technician_id,technician_avatar,lon,lat,serve_time,serve_time_end,technician_name')->select();
      $count=Technician::whereTime('serve_time','<',$timey)->whereTime('serve_time_end','>',$timey)->count();
       foreach ($technician as $key=>$value) {
         $value['distance'] = distance($lon, $lat, $value['lon'], $value['lat']);
       $value['count']=$count;
         $this->success('', $technician);
       }
       }else{
       $this->success('',$info);
     }

  }

}


/**
 * 数量÷总量乘以100
 */